package com.china.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.china.mapper.ChatHistoryMapper;
import com.china.mapper.ConversationMapper;
import com.china.pojo.ChatHistory;
import com.china.service.IChatHistoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ChatHistoryImpl extends ServiceImpl<ChatHistoryMapper, ChatHistory> implements IChatHistoryService {
    private final ConversationMapper conversationMapper;
    @Override
    public void saveChatHistory(String type,String chatId) {
        //判断数据库中是否已经存在  如果已经存在就返回，只有第一次才会添加
        //select * from chat_history where type = ? and conversation_id = ?
        Long count = lambdaQuery().eq(ChatHistory::getType, type)
                .eq(ChatHistory::getConversationId, chatId)
                .count();
        if (count != 0 && count > 1) {
            //有数据
            return;
        }
        //说明数据库没有存，这个是第一次
        ChatHistory build = ChatHistory.builder()
                .conversationId(chatId)
                .type(type)
                .title(chatId + type)
                .userId(null)
                .createTime(LocalDateTime.now())
                .build();
        this.save(build);
    }

    @Override
    public List<String> getChatIds(String type, Long userId) {
        //select * from chat_history where  type = ? and userId = ?
        List<ChatHistory> list = lambdaQuery()
                .eq(ChatHistory::getType, type)
                .eq(userId != null, ChatHistory::getUserId, userId)
                .list();
        return list.stream().map(ChatHistory::getTitle).toList();
    }
}